# 时间处理相关的库
import datetime, time, calendar
# 数学处理
import math, cmath, decimal
# web请求相关
import requests
# 异常处理
import traceback
# 数据库相关
import pymysql, redis
# 其他
from urllib import parse
import json, re, hashlib, ast
# 封装的包
from toolkit.http_tool import HttpTool
from toolkit.mysql_tool import MysqlTool
from toolkit.redis_tool import RedisTool
from toolkit.rocketmq_tool import RocketmqTool
from toolkit.kafka_tool import KafkaTool
from toolkit.sso_login_tool import SSOLoginTool
from toolkit.attestation_tool import SignatureTool
import re

import requests
import pymysql
import copy

env_type = now_type_text0
ecu = ecu
tar_type = tar_type_text0


class SwitchEnv:
    def __init__(self, ecu_str):
        self.headers = {
            "X-AUTH-SOURCE": "SSO",
            "Cookie": self.get_token(env_type),
            "Content-Type": "application/json; charset=UTF-8",
            'Connection': 'close'
        }
        self.ecu = ecu_str
        if env_type == "test":
            self.command_url = "http://test-os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/send"
            self.confirm_url = "http://test-os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/result"
        elif env_type == "online":
            self.command_url = "http://os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/send"
            self.confirm_url = "http://os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/result"
        elif env_type == "slave":
            self.command_url = "http://slave-os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/send"
            self.confirm_url = "http://slave-os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/result"
        elif env_type == "dev":
            self.command_url = "https://dev-os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/send"
            self.confirm_url = "http://dev-os-gateway.songguo7.com/api/iot/ste/control/cmd/batch/result"

        if tar_type == "test":
            self.tar_url = "DOMAIN=TEST-RADAR.SONGGUO7.COM:1024"
        elif tar_type == "online":
            self.tar_url = "DOMAIN=RADAR.SONGGUO7.COM:1024"
        elif tar_type == "slave":
            self.tar_url = "DOMAIN=SLAVE-RADAR.SONGGUO7.COM:1024"
        elif tar_type == "dev":
            self.tar_url = "DOMAIN=DEV-RADAR.SONGGUO7.COM:1024"

        self.req_params = self.get_req_params(self.tar_url)

    def req_command(self):
        res = requests.post(self.command_url, json=self.req_params, headers=self.headers)
        return res.json()

    def result_confirm(self, command_no):
        confirm_params = {
            "params": {
                "command_nos": [command_no]
            }
        }
        res = requests.post(self.confirm_url, json=confirm_params, headers=self.headers)
        return res.json()["data"][0]["command_result"]

    def get_token(self, env_type):
        db = pymysql.connect(host="10.100.73.74", port=3306, user="ttyc_57", password="OClgaa6YD!Rylnb5",
                             db="test_iot")
        cursor = db.cursor()
        sql = "SELECT * FROM test_iot.name_value where name = '{}_token'".format(env_type)
        cursor.execute(sql)
        data = cursor.fetchall()
        token = data[0][-1]
        db.close()
        cursor.close()
        return token

    def update_token(self, env_type):
        db = pymysql.connect(host="10.100.73.74", port=3306, user="ttyc_57", password="OClgaa6YD!Rylnb5",
                             db="test_iot")
        cursor = db.cursor()
        sql = '''UPDATE test_iot.name_value SET value = "''' + self.get_cookie(
            env_type) + '''" WHERE (name = '{}_token');'''.format(env_type)
        cursor.execute(sql)
        db.commit()
        db.close()
        cursor.close()

    def get_cookie(self, env_type):
        if env_type == "test":
            self.url = "http://test-sso-in.songguo7.com/sso/login"
            self.params = {
                "params": {
                    "login_name": "xingfengye",
                    "password": "e590ab8e56e8133aa5fb99e3f2ec9d4adad509fe"
                }
            }
        elif env_type == "online":
            self.url = "https://sso.songguo7.com/sso/login"
            self.params = {
                "params": {
                    "login_name": "xingfengye",
                    "password": "8197548f01ba4da1881ce3a8c76a24d1b7a381be"
                }
            }
        elif env_type == "slave":
            self.url = "http://slave-sso-in.songguo7.com/sso/login"
            self.params = {
                "params": {
                    "login_name": "xingfengye",
                    "password": "8197548f01ba4da1881ce3a8c76a24d1b7a381be"
                }
            }
            
        elif env_type == "dev":
            self.url = "http://dev-sso-in.songguo7.com/sso/login"
            self.params = {
                "params": {
                    "login_name": "xingfengye",
                    "password": "e590ab8e56e8133aa5fb99e3f2ec9d4adad509fe"
                }
            }
        res = requests.post(self.url, json=self.params)
        cookie = res.json()["data"]["access_token"]
        cookies = copy.deepcopy(cookie)
        return "sandbox_access_token=" + cookies + "; access_token=" + cookies

    def get_req_params(self, params):
        params = {
            "params": {
                "steStr": self.ecu,
                "channel_type": "NET",
                "command_type": "331",
                "need_ack": False,
                "ste_sns": [
                    self.ecu
                ],
                "tenant_code": "1",
                "param": params
            }
        }
        return params


def main_each(each_ecu):
    command_no = SwitchEnv(each_ecu).req_command()["data"]["send_success_commands"][0]["command_no"]
    command_result = SwitchEnv(each_ecu).result_confirm(command_no)
    c = 0
    while c < 5:
        if command_result == 0:
            command_result = SwitchEnv(each_ecu).result_confirm(command_no)
            time.sleep(3)
            c += 1
        elif command_result == 200:
            return "{} 切换环境成功！".format(each_ecu)
    else:
        return "{} 15s内查询不到结果，切换环境失败".format(each_ecu)


def main():
    SwitchEnv("123").update_token(env_type)
    res_list = []
    for each_ecu in re.findall('\d+', ecu):
        res_list.append(main_each(each_ecu))
    return "\n".join(res_list)
